package com.example.auv_660.auvorderload;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Point;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.example.auv_660.MainActivity;
import com.example.auv_660.autocontrolalgorithm.assistantsensor.BatterySensor;
import com.example.auv_660.autocontrolalgorithm.assistantsensor.LocationSensor;
import com.example.auv_660.autocontrolalgorithm.assistantsensor.OrientationSensor;
import com.example.auv_660.command.AUVBatteryCommand;
import com.example.auv_660.command.AUVDepthSensorCommand;
import com.example.auv_660.network.udp.HFUDPBuild;
import com.example.auv_660.util.Constants;
import com.example.auv_660.util.MsgType;
import com.example.auv_660.util.Tools;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class AUVInformationOrderLoad extends OrderLoad {
    private OrientationSensor orientationSensor;
    private MainActivity mainActivity = MainActivity.getInstance();
    private LocationSensor locationSensor;
    private BatterySensor batterySensor;
    private AUVDepthSensorCommand auvDepthSensorCommand;
    private AUVBatteryCommand auvBatteryCommand;
    private String selfPropeller;
    private String selfBattery;
    private String selfDepth;

    @Override
    public void doOrder(String order) {
        if (order.contains(Constants.CHECK_AUV_INFORMATION))
        {
            Constants.ORDER = false;

            mainActivity.sendMsgToMainThread(MsgType.CONTROLLER_MSG, "查询状态");

            orientationSensor = new OrientationSensor();

            if (mainActivity != null)
            {
                mainActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        locationSensor = new LocationSensor();
                    }
                });
            }

            batterySensor = new BatterySensor();

            try
            {
                Thread.sleep(10000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }

            selfPropeller = "异常";
            selfBattery = "异常";
            selfDepth = "异常";

            try
            {
                if (InetAddress.getByName(Constants.PROPELLER_IP).isReachable(100))
                {
                    selfPropeller = "正常";
                }

                if (InetAddress.getByName(Constants.BATTER_IP).isReachable(100))
                {
                    selfBattery = "正常";
                }

                if (InetAddress.getByName(Constants.DEPTH_SENSOR_IP).isReachable(100))
                {
                    selfDepth = "正常";
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            String longitude = "0";
            String latitude = "0";
            String accuracy = "0";
            String speed = "0";
            String time = "0";
            Location location = locationSensor.getLocation();
            if (location != null)
            {
                longitude = String.valueOf(location.getLongitude());
                latitude = String.valueOf(location.getLatitude());
                accuracy = String.valueOf(location.getAccuracy());
                speed = String.valueOf(location.getSpeed());
                time = Tools.getTime(location.getTime());
            }

            float[] orientationValues = orientationSensor.getValue();

            final Point p = new Point();
            Tools.getDisplay().getSize(p);

            final DisplayMetrics realdm;
            realdm = Tools.getRealMetrics();

            float xInches = realdm.widthPixels / realdm.xdpi;
            float yInches = realdm.heightPixels / realdm.ydpi;

            auvDepthSensorCommand = new AUVDepthSensorCommand();
            auvBatteryCommand = new AUVBatteryCommand();


            TelephonyManager telephonyManager = (TelephonyManager)
                    MainActivity.getInstance().getSystemService(Context.TELEPHONY_SERVICE);

            @SuppressLint("MissingPermission")
            //Tag
            //0
            String answer = Constants.CHECK_AUV_MODEL_STATE_ANSWER
            //手机传感器信息
            //1                 //2              //3              //4           //5
            + longitude + "," + latitude + "," + accuracy + "," + speed + "," + time + ","
            //6                          //7                          //8
            + orientationValues[0] + "," + orientationValues[1] + "," + orientationValues[2] + ","
            //9                                       //10
            + batterySensor.getCurrentBattery() + "," + " " + ","
            //手机信息
            //11                //12                //13                       //14                  //15
            + Build.BRAND + "," + Build.BOARD + "," + Build.MANUFACTURER + "," + Build.PRODUCT + "," + Build.DISPLAY
            //16                        //17
            + "," + p.x + " x " + p.y  +  "," + realdm.widthPixels / realdm.density + " x " + realdm.heightPixels / realdm.density
            //18                                                           //19
            + "," + Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)) + "," + Tools.getDisplay().getRefreshRate()
            //20                   //21                        //22
            + "," + Build.HARDWARE + "," + Constants.PHONEIMEI + "," + telephonyManager.getSimSerialNumber()
            //23                                                            //24
            + "," + getSubscriptionOperatorType(MainActivity.getInstance()) + "," + getNetworkState(MainActivity.getInstance())
            //25
            + "," + getIpAddress() + ","
            //舰体传感器信息
            //26                                         //27                                      //28                  //29               //30
            + auvBatteryCommand.getBatteryValue() + "," + auvDepthSensorCommand.getDepthAC() + "," + selfPropeller + "," + selfDepth + "," + selfBattery;

            System.out.println("answer: " + answer);

            HFUDPBuild.INSTANCE.getHFUdpClient().sendMessage("C" + answer);

            orientationSensor.unregister();
            locationSensor.stopLocation();
            batterySensor.releaseSource();

            Constants.ORDER = true;

            return;
        }
        else
        {
            OrderLoad nextOrder = this.getNextOrder();
            if (nextOrder != null)
            {
                nextOrder.doOrder(order);
            }
        }
    }

    public static String getNetworkState(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // 获取网络服务
        if (null == connManager) { // 为空则认为无网络
            return "无网络连接";
        }
        // 获取网络类型，如果为空，返回无网络
        NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
        if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
            return "无网络连接";
        }
        // 判断是否为WIFI
        NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (null != wifiInfo) {
            NetworkInfo.State state = wifiInfo.getState();
            if (null != state) {
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                    return "WIFI";
                }
            }
        }
        // 若不是WIFI，则去判断是2G、3G、4G网
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int networkType = telephonyManager.getNetworkType();
        switch (networkType) {

            // 2G网络
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return "2G";
            // 3G网络
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return "3G";
            // 4G网络
            case TelephonyManager.NETWORK_TYPE_LTE:
                return "4G";
            default:
                return "手机流量";
        }
    }

    private String getIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

            while (en.hasMoreElements()) {
                NetworkInterface ni = en.nextElement();
                Enumeration<InetAddress> enIp = ni.getInetAddresses();
                while (enIp.hasMoreElements()) {
                    InetAddress inet = enIp.nextElement();
                    if (!inet.isLoopbackAddress() && (inet instanceof Inet4Address)) {
                        ip += inet.getHostAddress().toString() + "\n";
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ip.substring(0, ip.length() - 1);
    }

    public String getSubscriptionOperatorType(Context context) {
        int opeType = -1;
        // No sim
        if (!hasSim(context)) {
            return "无Sim卡";
        }

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getNetworkOperator();
        // 中国联通
        if ("46001".equals(operator) || "46006".equals(operator) || "46009".equals(operator)) {
            return "中国联通";
            // 中国移动
        } else if ("46000".equals(operator) || "46002".equals(operator) || "46004".equals(operator) || "46007".equals(operator)) {
            return "中国移动";
            // 中国电信
        } else if ("46003".equals(operator) || "46005".equals(operator) || "46011".equals(operator)) {
            return "中国电信";
        } else {
            return "其他情况";
        }
    }

    private boolean hasSim(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getSimOperator();
        if (TextUtils.isEmpty(operator)) {
            return false;
        }
        return true;
    }
}
